package com.saic.localfileloader.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class Util {

	/** FTP_FILE TABLE */
	public static String fileSize = "file_size";//
	public static String checkTime = "check_time";//
	public static String createTime = "create_time";//
	public static String fileStats = "file_stats";//
	public static String fileName = "file_name";//
	public static String fileType = "file_type";//
	public static String recordLines = "record_lines";//
	public static String hbaseRecordTime = "hbase_record_time";//
	public static String hbaseRecordLines = "hbase_record_lines";//
	public static String oracleRecordTimes = "oracle_record_time";//
	public static String oracleRecordLines = "oracle_record_lines";//
	public static String uuid = "_UUID_";// Generate

	/** CSV_TMP/CSV_DONE/ORACLE DB */
	public static String col_1 = "col1";//
	public static String col_2 = "col2";//
	public static String col_3 = "col3";//
	public static String fileKey = "file_rowKey";//
	public static String upLoadDate = "uploadDate";// Year and month

	public static List<String> listFTP = new ArrayList<String>();
	static {// FTP file
		listFTP.add(fileName);
		listFTP.add(fileSize);
		listFTP.add(fileStats);
		listFTP.add(fileType);
		listFTP.add(checkTime);
		listFTP.add(createTime);
		listFTP.add(recordLines);
		listFTP.add(hbaseRecordTime);
		listFTP.add(hbaseRecordLines);
		listFTP.add(oracleRecordTimes);
		listFTP.add(oracleRecordLines);
		listFTP.add(uuid);
	}

	public static List<String> listCSV = new ArrayList<String>();
	static {
		listCSV.add(col_1);
		listCSV.add(col_2);
		listCSV.add(col_3);
		listCSV.add(uuid);// custom11
		listCSV.add(fileKey);// custom12
		listCSV.add(fileName);// custom13
		listCSV.add(upLoadDate);// custom14
	}

	/** Table name */
	public static String tab_ftp_file = "ftp_file";
	public static String tab_csv_tmp = "csv_tmp";
	public static String tab_csv_done = "csv_done";
	public static String tab_unique = "unique_check";

	public static String rowKey = "id";
	public static String flag_check = "flag_check";// custom10
	public static List<String> listUnique;// 仅存放Row Key
	static {
		listUnique = new ArrayList<String>();
		listUnique.add(rowKey);
	}

	public static String getMD5(String txt) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(txt.getBytes());
			byte[] b = md.digest();

			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @Get file name
	 * @param fileName
	 * @return
	 */
	public static String getFileName(String fileName) {
		return fileName.substring(0, 8);
	}

	/** Get the type of input file name */
	public static String getType(String filename) {
		String[] tmp = filename.split("\\.");
		return tmp[tmp.length - 1];
	}

	/**
	 * @Get stream NO
	 * @param fileName
	 * @return
	 */
	public static String getStreamNo(String fileName) {
		return fileName.substring(10, 23);
	}

	/**
	 * CSV_TMP/DONE table
	 */
	public static String getKey(Date createTime, String fileName, int lineNumber) {
		return Util.getMD5(fileName) + formatDate(createTime)
				+ formatNum(lineNumber);
	}

	/**
	 * FTP table
	 */
	public static String getKey(Date createTime, String fileName) {
		return Util.getMD5(fileName) + formatDate(createTime);
	}

	public static String getStartRow(String fileName) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, 0);
		return Util.getMD5(fileName) + formatDate(cal.getTime());
	}

	public static String getStopRow(String fileName) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MONTH, cal.getMaximum(Calendar.DAY_OF_MONTH));
		return Util.getMD5(fileName) + formatDate(cal.getTime());
	}

	public static String formatDate(Date time) {
		return new SimpleDateFormat("yyyy-mm-dd_HH:mm:ss").format(time);
	}

	public static String formatNum(int num) {
		return new DecimalFormat("000000").format(num);
	}

	/**
	 * @DESC:中文乱码问题
	 * @throws IOException
	 */
	public static void GBKReader(String src, String dst, String token,String charsetName)
			throws IOException {

		File dir = new File(src);
		File[] rsc = dir.listFiles(new FileFilter() {//
					public boolean accept(File pathname) {
						if (pathname.getName().endsWith(".txt"))
							return true;
						return false;
					}
				});
		new File(dst).mkdir();
		for (File f : rsc) {//
			File out = new File(dst + "/" + f.getName().split("\\.")[0]
					+ ".csv");
			String line = null;
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(f), charsetName));
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(out)));
			while (null != (line = br.readLine())) {
				System.out.println(line);
				bw.write(new String((line.replace(token, ",") + "\n")
						.getBytes(), "UTF-8"));
			}
			bw.flush();
			bw.close();
			br.close();
		}
	}

	public static void pm(Class<?> cls, String msg) {
		pm(cls.getName(), msg);
	}

	public static void pm(String cls, String msg) {
		System.out.println("Print by " + cls + "-->" + msg);
	}
}